<?php
/**
 * Created by PhpStorm.
 * User: 聪
 * Date: 2019/4/14
 * Time: 21:22
 */

namespace app\front\logic;


class Base
{
    protected static $default = 'zh';
    public static $user = [];
    const SUC_STATUS = 200;
    const ERR_STATUS = 500;

    public function __construct()
    {
        self::$user = request()->param('front_user');
    }

    public static function returnJson($ret = false, int $sucCode = 10000, int $errCode = 20000)
    {
        //设置语言版本;
        $lang = request()->header('accept-language');
        if (!empty($lang) && $lang != self::$default) {
            self::$default = substr($lang, 0, strrpos($lang, "-"));
        }

        //设置数据类型;
        if (is_object($ret)) $ret = $ret->toArray();

        //设置返回状态;
        if (empty($ret)) {
            $return['msg']    = self::error_msg($errCode);
            $return['code']   = $errCode;
            $return['status'] = self::ERR_STATUS;
        } else {
            $return['data']   = $ret;
            $return['msg']    = self::success_msg($sucCode);
            $return['code']   = $sucCode;
            $return['status'] = self::SUC_STATUS;
        }
        return json_encode($return);
    }

    public static function returnSuccess($ret = true, int $sucCode = 10000)
    {
        return json_encode([
            'status' => self::SUC_STATUS,
            'code'   => $sucCode,
            'msg'    => self::success_msg($sucCode),
            'data'   => $ret
        ]);
    }

    public static function returnError(int $errCode = 20000)
    {
        return json_encode([
            'status' => self::ERR_STATUS,
            'code'   => $errCode,
            'msg'    => self::error_msg($errCode),
        ]);
    }

    public static function error_msg(int $code)
    {
        $msg = [
            'zh' => [
                20000 => '暂无数据',
                20001 => '该手机号已被使用',
                20002 => '未知错误',
                20003 => '登录失败',
                20004 => '操作失败，请重新尝试',
                20005 => '该品牌已关注',
                20006 => '已收藏',
                20007 => '短信发送失败',
                20008 => '验证码不正确或已过期',
                20009 => '请勿重复上传',
                20010 => '下单失败',
            ]
        ];
        return $msg[self::$default][$code];
    }

    public static function success_msg(int $code)
    {
        $msg = [
            'zh' => [
                10000 => '拉取成功',
                10001 => '注册成功',
                10002 => '登录成功',
                10003 => '更新成功',
            ]
        ];
//        return $msg[static::$default][$code];
        return $msg['zh'][$code];
    }

}